package cz.proks.easyhelpdesk.gwt.utils;

import java.util.Date;

import com.google.gwt.user.client.Cookies;

import cz.proks.easyhelpdesk.api.model.Helpdesk;
import cz.proks.easyhelpdesk.api.model.User;

public class CookieUtils {
    private static final long COOKIE_TIMEOUT = 1000 * 60 * 60 * 24 * 365;
    private static final String USER_COOKIE_NAME = "easyHelpdesk_User";
    private static final String HELPDESK_COOKIE_NAME = "easyHelpdesk_Helpdesk";
    
    public static Long getCookieUserId() {
        String userCookieStr = Cookies.getCookie(USER_COOKIE_NAME); 
        return userCookieStr == null || userCookieStr.isEmpty() ? -1l : Long.valueOf(userCookieStr);
    }
    
    public static void setCookieUserId(Long userId) {
        userId = userId == null ? -1l : userId;
        
        if (userId == -1)
            Cookies.removeCookie(USER_COOKIE_NAME);
        else
            Cookies.setCookie(USER_COOKIE_NAME, String.valueOf(userId), new Date(new Date().getTime() + COOKIE_TIMEOUT));                
    }    
    
    public static void setCookieUser(User user) {
        setCookieUserId(user != null ? user.getId() : null);
    }
    
    public static Long getCookieHelpdeskId() {
        String helpdeskCookieStr = Cookies.getCookie(HELPDESK_COOKIE_NAME); 
        return helpdeskCookieStr == null || helpdeskCookieStr.isEmpty() ? -1l : Long.valueOf(helpdeskCookieStr);
    }
    
    public static void setCookieHelpdeskId(Long helpdeskId) {
        helpdeskId = helpdeskId == null ? -1l : helpdeskId;
        
        if (helpdeskId == -1)
            Cookies.removeCookie(HELPDESK_COOKIE_NAME);
        else
            Cookies.setCookie(HELPDESK_COOKIE_NAME, String.valueOf(helpdeskId), new Date(new Date().getTime() + COOKIE_TIMEOUT));                
    }    
    
    public static void setCookieHelpdesk(Helpdesk helpdesk) {
        setCookieHelpdeskId(helpdesk != null ? helpdesk.getId() : null);
    }
}
